<script setup lang="ts">
import dayjs from 'dayjs';

import { useGlobalStore, useSecuredStore } from '../../stores';
import { useWeatherApi, useHttpRequest } from '../../networks';

const securedStore = useSecuredStore();
const count = computed({
  get: () => securedStore.count,
  set: v => {
    securedStore.count = v;
  },
});

/** @type EChartsOption */
const opt = ref({
  title: {
    text: 'Echarts Demo',
    textStyle: {
      color: '#332277',
    },
  },
  tooltip: {
    show: true,
  },
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
  },
  yAxis: {
    type: 'value',
  },
  series: [
    {
      data: [count.value, 230, 224, 218, 135, 147, 260],
      type: 'bar',
    },
  ],
});

const resetCountToZero = ref(true);

watch(count, (countN, countO) => {
  opt.value.series[0].data[0] = countN;
  ElMessage.success({
    message: `Count changed by:${countN - countO}`,
    showClose: true,
    // offset: 0,
  });
});

const store = useGlobalStore();
const name = computed(() => store.name);

const weatherText = ref('Loading');
const loading = ref(true);
const svg = `
<svg viewBox="0 0 24 24">
  <path d="M10 17c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 
  2m6-9c1.1 0 2 .9 2 2v10c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V10c0-1.1.9-2 
  2-2h1V6c0-2.8 2.2-5 5-5s5 2.2 5 5v2h1m-6-5C8.3 3 7 4.3 7 
  6v2h6V6c0-1.7-1.3-3-3-3m12 10h-2V7h2v6m0 4h-2v-2h2v2z" />
</svg>`;
const buildWeatherText = (weatherInfo: any, date?: string) => {
  const weatherDesc: any = {
    '0': '晴',
    '1': '少云',
    '2': '多云',
    '3': '阴',
    '4': '雾',
    '5': '小雨',
    '6': '雨',
    '7': '雪',
    '8': '阵雨',
    '9': '雷雨',
  };
  let index = weatherInfo['daily']['time'].indexOf(date);
  let time = weatherInfo['daily']['time'][index];
  let weather =
    weatherDesc[weatherInfo['daily']['weathercode'][index].toString()[0]];
  let temperatureMax =
    weatherInfo['daily']['temperature_2m_max'][index] +
    weatherInfo['daily_units']['temperature_2m_max'];
  let temperatureMin =
    weatherInfo['daily']['temperature_2m_min'][index] +
    weatherInfo['daily_units']['temperature_2m_min'];
  return `${time}, ${weather}, ${temperatureMin} ~ ${temperatureMax}`;
};

const req = useHttpRequest();
onMounted(async () => {
  loading.value = true;
  try {
    let res = await req.get('https://api.open-meteo.com/v1/forecast', {
      params: {
        latitude: '39.91',
        longitude: '116.40',
        daily: 'weathercode,temperature_2m_max,temperature_2m_min',
        timezone: 'auto',
      },
    });
    if (res.status === 200) {
      weatherText.value = buildWeatherText(
        res.data,
        dayjs().format('YYYY-MM-DD'),
      );
    } else {
      weatherText.value = '载入天气时遇到错误';
    }
  } catch (err) {
    weatherText.value = '载入天气时遇到错误';
  }
  loading.value = false;
});

const api = useWeatherApi();
const isBj = ref(true);
const date = ref(new Date());
const filterDate = (date: Date) => {
  return (
    date.getTime() < Date.now() - 3600 * 1000 * 24 * 1 ||
    date.getTime() > Date.now() + 3600 * 1000 * 24 * 6
  );
};
const updateWeather = async () => {
  let loc;
  if (isBj.value) {
    loc = {
      latitude: '39.91',
      longitude: '116.40',
    };
  } else {
    loc = {
      latitude: '38.91',
      longitude: '121.60',
    };
  }
  let query = {
    ...loc,
    daily: 'weathercode,temperature_2m_max,temperature_2m_min',
    timezone: 'auto',
  };
  loading.value = true;
  let res = await api.get('/forecast', query);
  if (res) {
    weatherText.value = buildWeatherText(
      res,
      dayjs(date.value).format('YYYY-MM-DD'),
    );
  } else {
    weatherText.value = '载入天气时遇到错误';
  }
  loading.value = false;
};

watch(isBj, async isBj => {
  await updateWeather();
});
</script>

<template>
  <div class="flex flex-col justify-center items-center text-center">
    <div class="p-8">
      <blockquote>设置组件的msg属性来改变问候消息</blockquote>
      <header-message msg="Hello Demos"></header-message>
      <div>
        <blockquote>
          在设置页面设置含有英文字母的名字来测试持久存储和getter
        </blockquote>
      </div>
      <div>
        Hello {{ name }}, {{ store.uppercasedName }}, {{ store.lowercasedName }}
      </div>
      <div v-loading="loading" :element-loading-spinner="svg">
        <div>{{ weatherText }}</div>
        <el-switch
          active-text="北京"
          inactive-text="大连"
          v-model="isBj"
        ></el-switch>
        <el-date-picker
          @change="updateWeather"
          v-model="date"
          class="ml-4"
          type="date"
          :disabled-date="filterDate"
        ></el-date-picker>
      </div>
      <div class="flex justify-center items-center">
        编辑
        <span><i-ep-edit /></span>
        &nbsp;
        <code>views/Home/Demos.vue</code>
        &nbsp; 来测试热加载
      </div>
    </div>
    <div class="w-[50%] h-[30vh]">
      <v-chart :option="opt" autoresize></v-chart>
    </div>
    <el-button type="primary" @click="count++">
      count is {{ securedStore.count }}
    </el-button>
    <el-slider class="px-4" v-model="count"></el-slider>
    <el-button
      @click="securedStore.resetCount(resetCountToZero)"
      type="danger"
      plain
    >
      <i-ep:refresh-right class="animate-spin" />
    </el-button>
    <el-checkbox v-model="resetCountToZero">
      Reset to {{ resetCountToZero ? 0 : 100 }}
    </el-checkbox>
  </div>
</template>

<style lang="scss" scoped></style>
